package day03;

/**
 * @author Jetwang
 * @version 1.0
 * @since 2023/3/13 14:33
 * 顺时针打印矩阵
 *
 */
public class Offer29 {
    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return new int[0];
        }

        // 定义边界
        int l = 0, r = matrix[0].length - 1, t = 0, b = matrix.length - 1;
        int[] res = new int[(r + 1) * (b + 1)];
        int k = 0;

        while(true) {
            // 从左往右
            for (int i = t, j = l; j <= r; j++) {
                res[k++] = matrix[i][j];
            }
            t++;
            if (t > b) break;
            // 从上往下
            for (int i = t, j = r; i <= b; i++) {
                res[k++] = matrix[i][j];
            }
            r--;
            if (l > r) break;
            // 从右往左
            for (int i = b, j = r; j >= l ; j--) {
                res[k++] = matrix[i][j];
            }
            b--;
            if (t > b) break;
            // 从下往上
            for (int i = b, j = l; i >= t; i--) {
                res[k++] = matrix[i][j];
            }
            l++;
            if (l > r) break;
        }
        return res;
    }
}
